//
//  BDDetailReservationViewController.m
//  BadBoy
//
//  Created by wen on 2017/7/10.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDDetailReservationViewController.h"
#import "BDUserModel.h"
#import "BDDetailReservationInfoTableViewCell.h"
#import "BDShopInfoDeatilViewController.h"
#import "BDRefundViewController.h"
#import "BDReservationModel.h"
#import "BDOrderModel.h"
@interface BDDetailReservationViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *customCouponInfoView;
@property (nonatomic, strong) NSMutableArray *datasource;

@end

@implementation BDDetailReservationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"订单详情");
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    _customCouponInfoView = nil;
    
    if ([self.model isKindOfClass:[BDReservationModel class]]) {
        BDReservationModel *reservation = self.model;
        NSDecimalNumber *red_amount = [[NSDecimalNumber decimalNumberWithString:reservation.total_amount] decimalNumberBySubtracting:[NSDecimalNumber decimalNumberWithString:reservation.receipt_amount]];
        
        self.datasource = @[@[@{@"title":reservation.shop.title, @"image":@"dianpu", @"needJiantou":@""}],
                            @[@{@"title":ASLocalizedString(@"原价："), @"subTitle":[NSString stringWithFormat:@"¥%@", reservation.total_amount]},
                              @{@"title":ASLocalizedString(@"红包："), @"subTitle":[NSString stringWithFormat:@"-¥%@", red_amount]},
                              @{@"title":ASLocalizedString(@"合计："), @"subTitle":[NSString stringWithFormat:@"¥%@", reservation.receipt_amount]}]].mutableCopy;
    }else if ([self.model isKindOfClass:[BDOrderModel class]]) {
        BDOrderModel *order = self.model;
        NSDecimalNumber *receipt_amount = [[NSDecimalNumber decimalNumberWithString:order.total_amount] decimalNumberBySubtracting:[NSDecimalNumber decimalNumberWithString:order.hong_bao_amount]];
        
        self.datasource = @[@[@{@"title":order.shop_title, @"image":@"dianpu", @"needJiantou":@""}],
                            @[@{@"title":ASLocalizedString(@"原价："), @"subTitle":[NSString stringWithFormat:@"¥%@", order.total_amount]},
                              @{@"title":ASLocalizedString(@"红包："), @"subTitle":[NSString stringWithFormat:@"-¥%@", order.hong_bao_amount]},
                              @{@"title":ASLocalizedString(@"合计："), @"subTitle":[NSString stringWithFormat:@"¥%@", receipt_amount]}]].mutableCopy;
    }
    
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.datasource[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return self.customCouponInfoView.height;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return self.customCouponInfoView;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDDetailReservationInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reservationInfoCell" forIndexPath:indexPath];
    [cell configeWithModel:self.datasource[indexPath.section][indexPath.row]];
    if (indexPath.row == 0) {
        cell.isFirst = YES;
    }else {
        cell.isFirst = NO;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        //这里跳转到商家
        BDShopInfoDeatilViewController *infoVc = [[BDShopInfoDeatilViewController alloc] init];
        if ([self.model isKindOfClass:[BDReservationModel class]]) {
            BDReservationModel *reservation = self.model;
            infoVc.shopID = [NSString stringWithFormat:@"%@", @(reservation.shop.shop_id)];
            infoVc.title = reservation.shop.title;
        }else if ([self.model isKindOfClass:[BDOrderModel class]]) {
            BDOrderModel *order = self.model;
            infoVc.shopID = [NSString stringWithFormat:@"%@", @(order.shop_id)];
            infoVc.title = order.shop_title;
        }
        
        [self.navigationController pushViewController:infoVc animated:YES];
    }
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionFooterHeight = 0;
        _tableView.sectionHeaderHeight = 0;
        [_tableView registerClass:[BDDetailReservationInfoTableViewCell class] forCellReuseIdentifier:@"reservationInfoCell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.separatorInset = UIEdgeInsetsZero;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIView *)customCouponInfoView{
    if (!_customCouponInfoView) {
        self.customCouponInfoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0)];
        _customCouponInfoView.backgroundColor = [UIColor whiteColor];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = [UIFont systemFontOfSize:18];
        titleLabel.textColor = [UIColor colorWithHexString:@"#1c1c1c"];
        [_customCouponInfoView addSubview:titleLabel];
        
        UIImageView *imageView = [[UIImageView alloc] init];
        [_customCouponInfoView addSubview:imageView];
        
        UILabel *contnenLabel = [[UILabel alloc] init];
        contnenLabel.font = [UIFont systemFontOfSize:14];
        contnenLabel.textColor = [UIColor colorWithHexString:@"#767676"];
        contnenLabel.numberOfLines = 0;
        [_customCouponInfoView addSubview:contnenLabel];
        
        UIView *dashLine = [[UIView alloc] initWithFrame:CGRectMake(15, 0, kBDScreenWidth - 30, 1)];
        [dashLine drawLineLength:5 lineSpacing:2 lineColor:[UIColor colorWithHexString:@"#e0e0e0"] verticality:NO];
        [_customCouponInfoView addSubview:dashLine];
        
        UILabel *curentPriceLabel = [[UILabel alloc] init];
        curentPriceLabel.font = [UIFont systemFontOfSize:13];
        curentPriceLabel.textColor = [UIColor colorWithHexString:@"#767676"];
        [_customCouponInfoView addSubview:curentPriceLabel];
        
        UILabel *oldPriceLabel = [[UILabel alloc] init];
        oldPriceLabel.font = [UIFont systemFontOfSize:15];
        oldPriceLabel.textColor = [UIColor colorWithHexString:@"#767676"];
        [_customCouponInfoView addSubview:oldPriceLabel];
        
        UILabel *peopleNumberLabel = [[UILabel alloc] init];
        peopleNumberLabel.font = [UIFont systemFontOfSize:15];
        peopleNumberLabel.textColor = [UIColor colorWithHexString:@"#767676"];
        [_customCouponInfoView addSubview:peopleNumberLabel];
        
        UIButton *qianggouButton = [UIButton buttonWithType:UIButtonTypeCustom];
        qianggouButton.titleLabel.font = [UIFont systemFontOfSize:13];
        [_customCouponInfoView addSubview:qianggouButton];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.5)];
        line.backgroundColor = [UIColor colorWithHexString:@"#e0e0e0"];
        [_customCouponInfoView addSubview:line];
        
        UILabel *timeLabel = [[UILabel alloc] init];
        timeLabel.font = [UIFont systemFontOfSize:15];
        timeLabel.textColor = [UIColor colorWithHexString:@"#767676"];
        [_customCouponInfoView addSubview:timeLabel];
        
        if ([self.model isKindOfClass:[BDReservationModel class]]) {
            BDReservationModel *reservation = self.model;
            
            titleLabel.text = reservation.coupon.title;
            [titleLabel sizeToFit];
            titleLabel.top = 10;
            titleLabel.centerX = _customCouponInfoView.width / 2.0;
            
            [imageView sd_setImageWithURL:[NSURL URLWithString:reservation.coupon.cover] placeholderImage:[UIImage imageNamed:@"shop_moren.jpg"]];
            imageView.size = CGSizeMake(101, 76);
            imageView.top = titleLabel.bottom + 24;
            imageView.left = 15;
            
            contnenLabel.text = reservation.coupon.content;
            contnenLabel.width = kBDScreenWidth - imageView.right - 15 - 15;
            contnenLabel.height = [contnenLabel.text heightWithFont:contnenLabel.font width:contnenLabel.width];
            contnenLabel.left = imageView.right + 15;
            contnenLabel.top = imageView.top;
            
            dashLine.top = MAX(contnenLabel.bottom, imageView.bottom) + 20;

            NSString *string = [NSString stringWithFormat:ASLocalizedString(@"折扣价：¥%@"), [NSDecimalNumber decimalNumberWithString:reservation.coupon.discount_price]];
            NSMutableAttributedString *attribuString = [[NSMutableAttributedString alloc] initWithString:string];
            NSRange range = [string rangeOfString:[NSString stringWithFormat:@"¥%@", [NSDecimalNumber decimalNumberWithString:reservation.coupon.discount_price]]];
            [attribuString setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"ff4f00"]} range:range];
            curentPriceLabel.attributedText = attribuString;
            [curentPriceLabel sizeToFit];
            curentPriceLabel.left = 15;
            curentPriceLabel.top = dashLine.bottom + 15;
            
            oldPriceLabel.text = [NSString stringWithFormat:ASLocalizedString(@"原价：¥%@"), [NSDecimalNumber decimalNumberWithString:reservation.coupon.price]];
            [oldPriceLabel sizeToFit];
            oldPriceLabel.bottom = curentPriceLabel.bottom;
            oldPriceLabel.left = curentPriceLabel.right + 15;
            
            peopleNumberLabel.text = [NSString stringWithFormat:ASLocalizedString(@"推荐人数：%@人"), @(reservation.coupon.rec_num)];
            [peopleNumberLabel sizeToFit];
            peopleNumberLabel.top = curentPriceLabel.bottom + 15;
            peopleNumberLabel.left = 15;
            
            qianggouButton.size = CGSizeMake(65, 30);
            qianggouButton.centerY = peopleNumberLabel.top - 7.5;
            qianggouButton.right = kBDScreenWidth - 15;
            qianggouButton.layer.masksToBounds = YES;
            qianggouButton.layer.cornerRadius = 3;
            if (reservation.status == BDReservationStatusNotUse) {
                [qianggouButton setTitle:ASLocalizedString(@"申请退款")forState:UIControlStateNormal];
                [qianggouButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                qianggouButton.backgroundColor = [UIColor colorWithHexString:@"#ff992b"];
            }else if (reservation.status == BDReservationStatusUsed) {
                [qianggouButton setTitle:ASLocalizedString(@"再来一单")forState:UIControlStateNormal];
                [qianggouButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                qianggouButton.backgroundColor = [UIColor colorWithHexString:@"#ff992b"];
            }else if (reservation.status == BDReservationStatusOverdue) {
                [qianggouButton setTitle:ASLocalizedString(@"已失效")forState:UIControlStateNormal];
                [qianggouButton setTitleColor:[UIColor colorWithHexString:@"#767676"] forState:UIControlStateNormal];
                qianggouButton.backgroundColor = [UIColor whiteColor];
            }else if (reservation.status == BDReservationStatusRefunding) {
                [qianggouButton setTitle:ASLocalizedString(@"正在退款")forState:UIControlStateNormal];
                [qianggouButton setTitleColor:[UIColor colorWithHexString:@"#767676"] forState:UIControlStateNormal];
                qianggouButton.backgroundColor = [UIColor whiteColor];
            }else if (reservation.status == BDReservationStatusRefunded) {
                [qianggouButton setTitle:ASLocalizedString(@"已退款")forState:UIControlStateNormal];
                [qianggouButton setTitleColor:[UIColor colorWithHexString:@"#767676"] forState:UIControlStateNormal];
                qianggouButton.backgroundColor = [UIColor whiteColor];
            }else if (reservation.status == BDReservationStatusCommented) {
                [qianggouButton setTitle:ASLocalizedString(@"再来一单")forState:UIControlStateNormal];
                [qianggouButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                qianggouButton.backgroundColor = [UIColor colorWithHexString:@"#ff992b"];
            }
            
            [qianggouButton setEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
            [[qianggouButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                if (reservation.status == BDReservationStatusNotUse) {
                    //申请退款
                    BDRefundViewController *refundVC = [[BDRefundViewController alloc] init];
                    refundVC.reservation = reservation;
                    [self.navigationController pushViewController:refundVC animated:YES];
                }else if (reservation.status == BDReservationStatusUsed || reservation.status == BDReservationStatusCommented){
                    //在来一单
                }
            }];
            
            line.top = peopleNumberLabel.bottom + 15;
            
            timeLabel.text = [NSString stringWithFormat:ASLocalizedString(@"有效期：%@ 至 %@"), reservation.coupon.startTimeString, reservation.coupon.endTimeString];
            [timeLabel sizeToFit];
            timeLabel.centerY = line.bottom + 20;
            timeLabel.left = 15;
            
            _customCouponInfoView.height = line.bottom + 40;
        }else if ([self.model isKindOfClass:[BDOrderModel class]]) {
            BDOrderModel *order = self.model;
            
            titleLabel.text = order.coupon.title;
            [titleLabel sizeToFit];
            titleLabel.top = 10;
            titleLabel.centerX = _customCouponInfoView.width / 2.0;
            
            [imageView sd_setImageWithURL:[NSURL URLWithString:order.coupon.cover] placeholderImage:[UIImage imageNamed:@"shop_moren.jpg"]];
            imageView.size = CGSizeMake(101, 76);
            imageView.top = titleLabel.bottom + 24;
            imageView.left = 15;
            
            contnenLabel.text = order.coupon.content;
            contnenLabel.width = kBDScreenWidth - imageView.right - 15 - 15;
            contnenLabel.height = [contnenLabel.text heightWithFont:contnenLabel.font width:contnenLabel.width];
            contnenLabel.left = imageView.right + 15;
            contnenLabel.top = imageView.top;
            
            dashLine.top = MAX(contnenLabel.bottom, imageView.bottom) + 20;
            
            NSString *string = [NSString stringWithFormat:ASLocalizedString(@"折扣价：¥%@"), [NSDecimalNumber decimalNumberWithString:order.coupon.discount_price]];
            NSMutableAttributedString *attribuString = [[NSMutableAttributedString alloc] initWithString:string];
            NSRange range = [string rangeOfString:[NSString stringWithFormat:@"¥%@", [NSDecimalNumber decimalNumberWithString:order.coupon.discount_price]]];
            [attribuString setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"ff4f00"]} range:range];
            curentPriceLabel.attributedText = attribuString;
            [curentPriceLabel sizeToFit];
            curentPriceLabel.left = 15;
            curentPriceLabel.top = dashLine.bottom + 15;
            
            oldPriceLabel.text = [NSString stringWithFormat:ASLocalizedString(@"原价：¥%@"), [NSDecimalNumber decimalNumberWithString:order.coupon.price]];
            [oldPriceLabel sizeToFit];
            oldPriceLabel.bottom = curentPriceLabel.bottom;
            oldPriceLabel.left = curentPriceLabel.right + 15;
            
            peopleNumberLabel.text = [NSString stringWithFormat:ASLocalizedString(@"推荐人数：%@人"), @(order.coupon.rec_num)];
            [peopleNumberLabel sizeToFit];
            peopleNumberLabel.top = curentPriceLabel.bottom + 15;
            peopleNumberLabel.left = 15;
            
            qianggouButton.size = CGSizeMake(65, 30);
            qianggouButton.centerY = peopleNumberLabel.top - 7.5;
            qianggouButton.right = kBDScreenWidth - 15;
            qianggouButton.layer.masksToBounds = YES;
            qianggouButton.layer.cornerRadius = 3;
            qianggouButton.userInteractionEnabled = YES;
            [qianggouButton setTitle:ASLocalizedString(@"取消订单")forState:UIControlStateNormal];
            [qianggouButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            qianggouButton.backgroundColor = [UIColor colorWithHexString:@"#cccccc"];
            
            [qianggouButton setEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
            [[qianggouButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                NSString *url = [NSString stringWithFormat:@"%@payment/orders/%@", KBDBaseURL, @(order.my_id)];
                NSString *headValid = [BDUserModel getHeaderValidation];
                NSDictionary *para = @{@"id":@(order.my_id),
                                       @"status":@"7"};
                RACSignal *signal = [[BDNetworkingServer yy_PUT:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
                [signal subscribeNext:^(id  _Nullable x) {
                    [MBManager hideAlert];
                    [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"该订单取消成功")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:^(NSInteger index) {
                        [self.navigationController popViewControllerAnimated:YES];
                    }];
                }];
                [signal subscribeError:^(NSError * _Nullable error) {
//                    [MBManager hideAlert];
                    [MBManager showBriefAlert:ASLocalizedString(@"订单取消失败")clickHidden:YES clickBlock:nil];
                }];
            }];
            
            line.top = peopleNumberLabel.bottom + 15;
            
            timeLabel.text = [NSString stringWithFormat:ASLocalizedString(@"有效期：%@ 至 %@"), order.coupon.startTimeString, order.coupon.endTimeString];
            [timeLabel sizeToFit];
            timeLabel.centerY = line.bottom + 20;
            timeLabel.left = 15;
            
            _customCouponInfoView.height = line.bottom + 40;
        }
    }
    return _customCouponInfoView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
